package com.kd.d5000acquire.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
@Data
@Slf4j
public class TcpClient {

    @Resource(name = "myMessageQueue")
    private Queue queue ;

    @Value("${my.isShortConnect}")
    private boolean isShortConnect;

    private ChannelHandler channelHandler;


    @Value("${my.alarmtransfer.host}")
    public String host;
    @Value("${my.alarmtransfer.port}")
    public int port;

    //@Scheduled(fixedDelay = 1000)
    public void start() {
        log.info("开始链接tcp" +
                "\n参数为:" +
                "\n参数host:"+ host +
                "\n参数port:"+ port);
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ServerClientHandler());
                        }
                    });
            ChannelFuture cf = b.connect().sync();
            log.info("tcp链接成功");
            do {
                String message = (String) queue.poll();
                if(message == null){
                    continue;
                }
                log.info("准备发送消息,消息内容为:"+ message.toString());
                cf.channel().writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
            } while (!isShortConnect);
            cf.channel().closeFuture().sync();
        } catch (Exception e){
            log.error("Tcp连接异常",e);
        } finally {
            try {
                log.info("关闭TCP连接");
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
